<template>

  <el-card>
    <el-button type="primary" :icon="Plus" @click="showSaveOrUpdateTrademark()">品牌添加</el-button>

    <el-table v-loading="loading" :data="trademarkList" border class="trademarkTable">
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column prop="tmName" label="品牌名称" />
      <el-table-column label="品牌LOGO">
        <template v-slot="{ row }">
          <img :src="row.logoUrl" class="trandemarkImg" />
        </template>
      </el-table-column>

      
      <el-table-column prop="address" label="操作" width="120">
        <template v-slot="{ row }">
        <el-button type="warning" :icon="Edit" size="small" @click="showSaveOrUpdateTrademark(row)" />
        <el-button type="danger" :icon="Delete" size="small" @click="showRemoveTrademark(row)"/>
      </template>
      </el-table-column>
    
    </el-table>
    <el-pagination
      v-model:currentPage="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[3, 6, 9]"
      :total="total"
      layout=" prev, pager, next, jumper,->,total, sizes,"
      @size-change="getTrademarkList"
      @current-change="getTrademarkList"
    />

    <el-dialog v-model="Visible" title="添加品牌">
      <el-form label-width="120px" ref="TrademarkFormRef" :model="TrademarkFormDate" :rules="TrademarkRules">
        <!-- prop指定当前表单项使用哪个表单校验规则 -->
        <el-form-item label="品牌名称" prop="tmName">
          <el-input v-model="TrademarkFormDate.tmName" />
        </el-form-item>

        <el-form-item label="品牌LOGO" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            :action="UPLOAD_URL_PREFIX + `/admin/product/fileUpload`"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="TrademarkFormDate.logoUrl" :src="TrademarkFormDate.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">只能上传jpg/png文件，且不超过200kb</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="Visible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>

  <div>Trademark</div>

</template>

<script lang="ts">
export default {
  name: "XTrademark",
};
</script>

<script lang="ts" setup>
import { Plus, Edit, Delete } from "@element-plus/icons-vue";
import { ref } from "vue";

import { getTrademarkListApi, saveTrademarkApi ,updateTrademarkApi,removeTrademarkApi} from "@/api/product/trademark";
import { onMounted } from "vue";
import type { TrademarkList,TrademarkItem } from "@/api/product/model/trademarkModel";
import { ElMessage,ElMessageBox  } from "element-plus";
import type { UploadProps } from "element-plus";
import { reactive } from "vue";
import type { FormInstance, FormRules } from "element-plus";
const currentPage = ref(1);
const pageSize = ref(3);
const total = ref(0);
const loading = ref(false);
/**************************** 品牌删除 ********************************/
const showRemoveTrademark = (row:TrademarkItem) => {
  ElMessageBox.confirm(`您确认要删除 ${row.tmName} 吗?`, "删除",
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
      await removeTrademarkApi(row.id)
      ElMessage("删除品牌成功")
      getTrademarkList();
    })
    .catch(() => {
      ElMessage("删除品牌失败")
    })
}
/**************************** 表单校验及发请求添加品牌 ********************************/
const TrademarkFormRef = ref<FormInstance>();
const TrademarkFormDate = reactive({
  tmName: "",
  logoUrl: "",
  id: 0,
});
const TrademarkRules = reactive<FormRules>({
  tmName: [
    { required: true, message: "请输入品牌名称", trigger: "blur" },
    { min: 2, max: 10, message: "品牌名称长度只能为2-10位", trigger: "blur" },
  ],
  // 上传图片组件没法失去焦点，不需要trigger: "blur"
  logoUrl: [{ required: true, message: "请上传品牌LOGO" }],
});
const submitForm = () => {
  // 对整个表单进行校验
  TrademarkFormRef.value?.validate(async(valid) => {
    // ?. 可选链，前面有值就会执行后面代码，没值就不执行了
    if (valid) {
      const { tmName, logoUrl ,id} = TrademarkFormDate;
      if(id){ //有id修改品牌
        await   updateTrademarkApi({tmName, logoUrl ,id})
      }else{
      await  saveTrademarkApi(tmName, logoUrl);
      }
      
      ElMessage.success(`${id ? "修改" : "添加"}品牌成功`);
      // 清空表单内容
      // TrademarkFormDate.tmName=""
      // TrademarkFormDate.logoUrl=""
      Visible.value = false;
      getTrademarkList();
      // console.log("表单校验通过");
    }
  });
};



//添加品牌对话框显示&隐藏的标识
const Visible = ref(false);
//显示添加品牌
// const showTrademark = () => {
//   Visible.value = true;
// };
//品牌修改
const showSaveOrUpdateTrademark=(row:TrademarkItem={ tmName: "", logoUrl: "", id: 0 })=>{
  Visible.value = true
  TrademarkFormDate.tmName=row.tmName
      TrademarkFormDate.logoUrl=row.logoUrl
      TrademarkFormDate.id=row.id;
      TrademarkFormRef.value?.clearValidate();
}

const trademarkList = ref<TrademarkList>([]);
/**************************** //上传图片 ********************************/

// 请求前缀
const UPLOAD_URL_PREFIX = import.meta.env.VITE_API_URL;
// const imageUrl = ref("");

const handleAvatarSuccess: UploadProps["onSuccess"] = (response, uploadFile) => {
  TrademarkFormDate.logoUrl = response.data;
  // 上传成功，清空图片表单失败信息
  TrademarkFormRef.value?.clearValidate(["logoUrl"]);
};
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  const imgType = ["image/jpeg", "image/jpg", "image/png", "image/jpeg"];
  if (!imgType.includes(rawFile.type)) {
    ElMessage.error("上传的图片必须是jpg或png格式!");
    return false;
  } else if (rawFile.size / 1024 > 500) {
    ElMessage.error("上传的图片不能超过500kb!");
    return false;
  }
  return true;
};
//封装一个函数
const getTrademarkList = async () => {
  loading.value = true;
  const res = await getTrademarkListApi(currentPage.value, pageSize.value);
  // console.log(res)
  trademarkList.value = res.records;
  total.value = res.total;
  loading.value = false;
  ElMessage.success("获取品牌分页列表成功");
};
onMounted(() => {
  getTrademarkList();
});
</script>

<style scoped>
.trademarkTable {
  margin: 20px;
}
.trandemarkImg {
  width: 100px;
}
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>
<style>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
